import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isAdd: [],
    allNum: []
  },
  mutations: {
    add (state, goods) {
      if (state.allNum.length === 0) {
        var goodsNum = {
          name: goods.name,
          num: 1,
          price: goods.price
        }
        state.allNum.push(goodsNum)
        // console.log(goodsNum)
      } else {
        var index = state.allNum.findIndex(val => val.name === goods.name)
        // console.log(index)
        if (index !== -1) {
          var obj = {name: state.allNum[index].name, num: ++state.allNum[index].num, price: state.allNum[index].price}
          // console.log(obj)
          state.allNum.splice(index, 1, obj)
        } else {
          var newobj = {name: goods.name, num: 1, price: goods.price}
          state.allNum.push(newobj)
          // console.log(newobj)
        }
      }
      // console.log(state.allNum)
      if (state.isAdd.includes(goods.name)) return
      state.isAdd.push(goods.name)
      // console.log(state.isAdd)
    },
    remove (state, name) {
      var index = state.allNum.findIndex(val => val.name === name)
      --state.allNum[index].num
      if (state.allNum[index].num === 0) {
        var index2 = state.isAdd.findIndex(val => val === name)
        // console.log(index2)
        state.isAdd.splice(index2, 1)
        // console.log(state.isAdd)
        state.allNum.splice(index, 1)
        // console.log(state.allNum)
        return false
      }
      var obj = {name: state.allNum[index].name, num: state.allNum[index].num, price: state.allNum[index].price}

      state.allNum.splice(index, 1, obj)
      // console.log(state.allNum)
      // console.log(state.isAdd)
    },
    clear (state) {
      state.isAdd = []
      state.allNum = []
    }
  },
  getters: {
    showNumByName: (state) => (name) => {
      var val = state.allNum.find(val => val.name === name)
      if (!val) return false
      return val.num
    },
    showAllNum: (state) => {
      var num = 0
      state.allNum.forEach(element => {
        num += element.num
      })
      return num
    },
    showPriceByName: (state) => (name) => {
      var val = state.allNum.find(val => val.name === name)
      if (!val) return false
      return val.price
    },
    showAllPrice: (state) => {
      var price = 0
      state.allNum.forEach(element => {
        price += element.price * element.num
      })
      return price
    },
    showAll: (state) => {
      return state.allNum
    }
  }
})
